package com.nari.kmd_dataservice.interceptor;

import com.nari.kmd_dataservice.constant.ConstantParameter;
import com.nari.kmd_dataservice.constant.GlobalVariable;
import com.nari.kmd_dataservice.util.SM3;
import com.nari.kmd_dataservice.util.SM4;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @ClassName: HeaderModifierAdvice
 * @Description: 响应body进行sm3校验加密设置响应头
 * @Author: zhangnaijiang
 * @Date: 2022/01/22 03:35
 * @Version 1.0.0
 */
@ControllerAdvice
@Slf4j
public class HeaderModifierAdvice implements ResponseBodyAdvice<Object> {
    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                                  Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request,
                                  ServerHttpResponse response) {
        ServletServerHttpResponse servletServerHttpResponse = (ServletServerHttpResponse)response;
        HttpServletResponse httpServletResponse = servletServerHttpResponse.getServletResponse();
        String requestURI = request.getURI().getPath();
        log.info("requestURI="+requestURI);
        if("/server/test".equals(requestURI) || !GlobalVariable.checkSM4) {
            String sign = "";
            if (body instanceof String) {
                sign = SM3.encrypt((String)body);
            }
            httpServletResponse.setHeader("sign", sign);
            log.info("明文响应sign：{}，参数：{}",sign, body);
            return body;
        }
        if (body instanceof String) {
            String encryptBody = SM4.encryptEcb(ConstantParameter.localSM4Key, (String)body);
            String sign = SM3.encrypt(encryptBody);
            httpServletResponse.setHeader("sign", sign);
            log.info("密文响应sign：{}，参数：{}，加密{}",sign, body, encryptBody);
            return encryptBody;
        }
        log.error("其他响应{}",body);
        return body;
    }
}